<?php

class ImageController extends Zend_Controller_Action
{

    public function indexAction()
    {
        $this->_redirect('/');
    }
    
    public function imageAction()
    {
        Zend_Layout::getMvcInstance()->disableLayout();
        $id = $this->_getParam('id', 0);
        $width = $this->_getParam('width');
        $height = $this->_getParam('height');
        $overScale = intval($this->_getParam('overScale', 0));
        $overScale = $overScale == 0 ? 0 : 1;
        $type = $this->_getParam('type');
        $file = implode('_', array($width, $height, $overScale)) . '.jpg';
        $cachePath = APPLICATION_PUBLIC . '/images/' . $id;
        if (!file_exists($cachePath)) {
            mkdir($cachePath, 0777, true);
        }
        $cachePath .= '/' . $file;
        if (file_exists($cachePath)) {
            $content = file_get_contents($cachePath);
            header('Content-Type: image/jpg');
            die($content);
        }
        $path = realpath(APPLICATION_PATH . '/../uploaded/image/') . '/' . $id . '.jpg';
        if (!file_exists($path)) {
            $path = realpath(APPLICATION_PATH . '/../uploaded/image/') . '/0.jpg';
        }
        $imgUtils = new My_ImageUtils();
        $imgUtils->load($path);
        $imgUtils->resizeToBounds($width, $height, $overScale);
        $imgUtils->save($cachePath);
        $content = file_get_contents($cachePath);
        header('Content-Type: image/jpg');
        die($content);
    }

}

